package ca.usask.cs.Gui;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.ButtonGroup;
import javax.swing.JFileChooser;
import javax.swing.JTextField;

import ca.usask.cs.decisiontree.DecisionTree;
import ca.usask.cs.decisiontree.XMLHandler.XMLController;
import  org.jdesktop.layout.GroupLayout;

import processing.core.PApplet;

/*
 * a class can export xml and dot file
 * @author Wenyi An
 * May,2010
 */
public class BuildPictureGui extends javax.swing.JFrame {

	private InterfaceHandler interfaceHandler;
	private XMLController xmlCtrl;
    /** Creates new page for draw a picture of tree */
	final private boolean isGraphicalInterfaceToBeDisplayed;
    public BuildPictureGui(InterfaceHandler interfaceHandler, boolean paramIsGraphicalInterfaceToBeDisplayed) {
    	this.interfaceHandler=interfaceHandler;
    	isGraphicalInterfaceToBeDisplayed = paramIsGraphicalInterfaceToBeDisplayed;
    	
        initComponents();
    }
 @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jButton3 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
//        jRadioButton1 = new javax.swing.JRadioButton();
//        jRadioButton2 = new javax.swing.JRadioButton();
        jLabel7 = new javax.swing.JLabel();
        buttonGroupforRollback = new ButtonGroup();
        
        setDefaultValue();
       
        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(262, 262, 262)
                .add(jButton2)
                .addContainerGap(289, Short.MAX_VALUE))
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .add(88, 88, 88)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(jLabel3)
                        .add(258, 258, 258))
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jLabel1)
                            .add(jLabel2)
                            .add(jLabel7, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 77, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .add(18, 18, 18)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                                .add(1, 1, 1)
                                .add(jLabel6, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 241, Short.MAX_VALUE))
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, jTextField2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE)
                            .add(jTextField1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE)
                            .add(jTextField3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE)
                            .add(jLabel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE)
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE)
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                                
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 56, Short.MAX_VALUE)
                                ))))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jButton1)
                    .add(jButton3))
                .add(106, 106, 106))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(30, 30, 30)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                   
                    .add(jLabel7))
                .add(18, 18, 18)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel1)
                    .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(11, 11, 11)
                .add(jLabel4)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel3)
                    .add(jTextField3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jButton3))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jLabel5)
                .add(13, 13, 13)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jButton1)
                    .add(jLabel2)
                    .add(jTextField2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jLabel6)
                .add(18, 18, 18)
                .add(jButton2)
                .addContainerGap(35, Short.MAX_VALUE))
        );


        jLabel2.getAccessibleContext().setAccessibleName("Dot File by Note");

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-624)/2, (screenSize.height-348)/2, 624, 348);
    }// </editor-fold>

   

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton2;
	private ButtonGroup buttonGroupforRollback;
    // End of variables declaration
    public void setDefaultValue(){
    	 setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

         jLabel1.setText("RollBack Value");

         if (this.interfaceHandler.catchRollBackValue()!=Double.NaN){
        	 jTextField1.setText(Double.toString(this.interfaceHandler.catchRollBackValue()));
        	 jTextField1.setEditable(false);
         }
          else{
        	  jTextField1.setText("0.0");
        	  jTextField1.setEditable(false);
          }       
         jLabel2.setText("Dot File by Note");
         jTextField3.setText("C:\\tmp\\output.xml");   
         jButton1.setText("Browse");
         jButton1.addActionListener(new FileChooserListener(jTextField2,"C:\\tmp\\output.dot"));
         jButton2.setText("Done");
         jButton2.addActionListener(new dotSaveListener());
         jLabel3.setText("Tree Output File");
         jTextField2.setText("C:\\tmp\\output.dot");
         jButton3.setText("Browse");
         jButton3.addActionListener(new FileChooserListener(jTextField3,"C:\\tmp\\output.xml"));
         jLabel4.setText("");
         jLabel4.setForeground(new Color(255, 0, 0));
         jLabel5.setText("");
         jLabel5.setForeground(new Color(255, 0, 0));
         jLabel6.setText("");
         jLabel6.setForeground(new Color(255, 0, 0));
//         jRadioButton1.setText("Max Value");
//
//         jRadioButton2.setText("Min Value");

     //    jLabel7.setText("Choose RollBack Value");
         buttonGroupforRollback.add(jRadioButton1);
         buttonGroupforRollback.add(jRadioButton2);
    }
    
    /**
	 * The listener for the press of the submit button.
	 * When it happens, obtain the data values from the fields, and
	 * create the ward.  Afterwards, create and make visible the window
	 * with the main options for the user.
	 */
	
	private class dotSaveListener implements ActionListener
	{		
		public void actionPerformed (ActionEvent event)
		{
			try{
				checkXML();
			}
			catch(Exception e){
				jLabel5.setText("*" + e.getMessage());
				return;
			}
			try{

			
				
		//		ca.usask.cs.drawTree.DrawControler.
				if (isGraphicalInterfaceToBeDisplayed)
				{
					xmlCtrl = interfaceHandler.getMainControler().returnXmlCtr();
					ca.usask.cs.drawTree.DrawControler.CopyFromXMLtreeNodeList = xmlCtrl.getTreeNodeList();
					ca.usask.cs.drawTree.DrawControler.CopyTree = (DecisionTree) interfaceHandler.controller.getTreeSturcture().getBasicDecisionTree().clone();
					PApplet.main(new String[] { "--present",
					"ca.usask.cs.drawTree.DrawControler" });
				}

				jLabel6.setText("Output of XML file complete.  Closing.");
				System.exit(0);

			}
			catch(Exception e){
				jLabel6.setText("*" +e.getMessage());
				return;
			}
		}
		
		
		private void checkXML() throws Exception{
			if(jTextField3.getText().trim().length() != 0){				// if we have text specified for the tree output xml filename
				if(!jTextField3.getText().trim().endsWith(".xml")){
					System.err.println("Could not generate XML file due to invalid name" + jTextField3.getText());
					throw new Exception("Not a xml file: " + jTextField3.getText().trim());
				}
				File file1 = new File(jTextField3.getText().trim());
				if(!file1.exists()&&!file1.isFile()){
					File creatfile1 = new File(jTextField3.getText().trim());
			
					try {
						creatfile1.createNewFile();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						System.err.println("Could not generate XML file due to exception" + e.getStackTrace());
						throw new Exception("Can not create XML file");
					}
				}

				System.err.println("Attempting to generate XML file...");
				interfaceHandler.controller.writeToXML(jTextField3.getText().trim());	
				System.err.println("Finished attempting to generate XML file...");

			}
			else{
				throw new Exception("Empty field");
			}
		}
		
	}
    // End of variables declaration
    /**
	 * The listener for the press of the browse button.
	 * When it happens, the users can choose the location 
	 * of the file
	 */

	private class FileChooserListener implements ActionListener
	{	
		private JTextField jTextField;
		private String location;
		public FileChooserListener(JTextField jTextField,String location){
			this.jTextField = jTextField;
			this.location = location;
		}
		
		public void actionPerformed(ActionEvent e) {
			   JFileChooser c = new JFileChooser();
			   // Demonstrate "Open" dialog:
			   int rVal = c.showOpenDialog(BuildPictureGui.this);			 		        
			   if (rVal == JFileChooser.APPROVE_OPTION) {
				   jTextField.setText(c.getCurrentDirectory().toString()+"\\"+c.getSelectedFile().getName());
			   }
			   if (rVal == JFileChooser.CANCEL_OPTION) {
				   jTextField.setText(location);
			    
			   }
			 }
	}
	private static final long serialVersionUID = 1;
}